package com.jumper.property.comparer.starter.mybatis;

import com.jumper.property.comparer.core.enums.LogTable;
import com.jumper.property.comparer.core.support.LogRepository;
import com.jumper.property.comparer.core.support.param.LogPageParam;
import com.jumper.property.comparer.core.support.result.LogEntity;
import com.jumper.property.comparer.core.support.result.LogEntityPage;
import lombok.AllArgsConstructor;

import java.util.ArrayList;
import java.util.List;


@AllArgsConstructor
public class MybatisLogRepositoryImpl implements LogRepository {

    private final BusOptLogMapper mapper;

    @Override
    public void save(LogTable busType, List<LogEntity> optLogs) {
        optLogs.forEach(optLog -> {
            mapper.insert(busType.getLogTableName(), optLog);
        });
    }

    @Override
    public LogEntityPage getLogsPage(LogTable busType, LogPageParam pageParam) {
        List<LogEntity> logs = new ArrayList<>();
        int pageNum = pageParam.getPageNum();
        int pageSize = pageParam.getPageSize();
        int offset = ((pageNum - 1) * pageSize);
        int count = mapper.count(busType.getLogTableName(), pageParam.getDataKey());
        if (count > 0) {
            logs = mapper.select(busType.getLogTableName(), pageParam.getDataKey(), offset, pageSize);
        }
        return new LogEntityPage(pageNum, pageSize, count, logs);
    }
}
